<template>
  <el-dialog v-model="isShow" draggable width="720" :close-on-click-modal="false">
    <template #header>
      {{ data.title }}
    </template>
    <el-form :model="data">
      <div class="form-item-row">
        <el-form-item label="操作员姓名" :label-width="sLabel[0]">
          <el-input
            v-model="data.name"
            :disabled="hasStr('status,power,psw',data.flag)"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-tag
            :type="data.status == 0 ? 'success' : 'danger'"
            style="margin: 0 5px"
            >{{ data.status== 0 ? '正常' : '停用' }}</el-tag
          >
        </el-form-item>
      </div>
      <div class="form-item-row">
        <el-form-item label="联系电话" :label-width="sLabel[0]">
          <el-input
            v-model="data.phone"
            :disabled="hasStr('status,power,psw',data.flag)"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-tag style="margin: 0 5px">联系电话同时作为登录账号使用</el-tag>
        </el-form-item>
      </div>
      <div class="form-item-row" v-if="data.flag == 'add'">
        <el-form-item label="登录密码" :label-width="sLabel[0]">
          <!-- <el-input
            v-model="data.password"
            type="password"
            show-password
            :disabled="hasStr('status,power',data.flag)"
          ></el-input> -->
        </el-form-item>
        <el-form-item>
          <!-- <el-tag type="warning" style="margin: 0 5px">密码不小于8位，且需包含大小写字母、数字、特殊字符</el-tag> -->
          <el-text type="danger">初始登录密码为<el-tag type="warning" style="margin: 0 5px">{{data.password}}</el-tag>请创建后请尽快修改</el-text>
        </el-form-item>
      </div>
      <!-- <div class="form-item-row" v-if="data.flag == 'add'">
        <el-form-item label="再次输入密码" :label-width="sLabel[0]">
          <el-input
            v-model="data.password2"
            type="password"
            show-password
            :disabled="hasStr('status,power',data.flag)"
          ></el-input>
        </el-form-item>
      </div> -->
      <div class="form-item-row">
        <el-form-item label="所属用户" :label-width="sLabel[0]">
          <el-select
            v-model="clientName"
            filterable
            remote
            reserve-keyword
            placeholder="输入用户名称关键字查询"
            @click="getClientByName('')"
            remote-show-suffix
            :remote-method="getClientByName"
            :loading="loading"
            @change="clientChange"
            :disabled="hasStr('status,power,psw',data.flag)"
          >
            <el-option
              v-for="item in clientOptions"
              :key="item.Id"
              :label="item.name"
              :value="item.Id"
            />
          </el-select>
        </el-form-item>
      </div>
      <div class="form-item-row" v-if="data.dtCreate != ''">
        <el-form-item label="创建时间" :label-width="sLabel[0]">
          <span class="label">{{ data.dtCreate }}</span>
        </el-form-item>
        <el-form-item label="操作员" :label-width="sLabel[1]">
          <span class="label">{{ data.operCreate }}</span>
        </el-form-item>
      </div>
      <div class="form-item-row" v-if="data.dtUpdate != ''">
        <el-form-item label="修改时间" :label-width="sLabel[0]">
          <span class="label">{{ data.dtUpdate }}</span>
        </el-form-item>
        <el-form-item label="操作员" :label-width="sLabel[1]">
          <span class="label">{{ data.operUpdate }}</span>
        </el-form-item>
      </div>
      <div class="form-item" v-if="data.flag == 'power'">
        <div v-if="isAdmin(data.name)">
          <el-text type="primary" style="font-size: 18px;margin-left: 80px;">当前操作员拥有全部权限</el-text>
        </div>
        <div class="title" v-else>
          <el-text type="primary" style="font-size: 18px;margin: 0 10px;">权限设置</el-text>
          <el-checkbox v-model="allChecked" @change="allCheckedAction">全选</el-checkbox>
        </div>
        <div class="power" v-if="!isAdmin(data.name)">
          <el-checkbox-group  class="item" v-for="item in powerList" :key="item.label" v-model="powerChecked">
            <el-checkbox :label="item.label" size="large" />
          </el-checkbox-group>
        </div>
        
      </div>
      <div class="form-item" v-if="data.flag == 'psw'">
        <el-form-item label="" :label-width="sLabel[0]">
          <el-tag size="large" type="danger">
            点击确定将当前操作员密码重置为
            <el-tag type="warning" style="margin: 0 5px" effect="dark">{{data.default_password}}</el-tag>
          </el-tag>
        </el-form-item>      
      </div>
    </el-form>
    <template #footer>
      <div>
        <el-button @click="close()">取 消</el-button>
        <el-button v-if="hasStr('add,power',data.flag)" type="primary" @click="done()" :loading="loading">确 定</el-button>
        <el-button v-if="data.flag == 'status'" type="danger" @click="msgBox('status',data.status == 0?'停用此操作员':'取消停用')">{{
          data.status == 0 ? "停 用" : "取消停用"
        }}</el-button>
        <el-button v-if="data.flag == 'psw'" type="danger" @click="msgBox('psw','重置当前操作员密码')">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { getCurrentInstance, reactive, ref } from "vue-demi";
import http from "@/axios/http";
import util from "@/assets/js/util";
import { ElMessageBox, ElNotification } from "element-plus";
import mqtt from '@/assets/js/mqtt';
export default {
  setup(props, ctx) {
    const Global = getCurrentInstance().proxy
    let user = reactive({
      id: Global.$var.user.id,
      username: Global.$var.user.username,
      power: Global.$var.user.power,
    });
    let powerPool = Global.$const.POWER_POOL
    function mqttOnMsg() {
      mqtt.onMsg((t,m)=>{
        loading.value = false
        let r = JSON.parse(m)
        if (r.data.returnCode == 10000) {
          let d = r.data.data
          if (r.msgType == 52 || r.msgType == 54 || r.msgType == 55 || r.msgType == 58) {
            // console.log(d)
            if (r.msgType == 58) {
              ElNotification({
                type: 'success',
                duration: 1500,
                message: '密码重置成功'
              })
            }
            ctx.emit("done", data);
            isShow.value = false;
          }
          if (r.msgType == 57) {
            console.log(d)
            allChecked.value = false
            let pp = powerPool.platuser
            if (data.plat_user.scope == '1000') {
              pp = powerPool.system
            }
            let pd = []
            for (let i in d) {
              if (isNull(d[i])) continue;
              let hs = util.hasStr(pp,','+d[i].value+',')
              if (hs) {
                d[i].label = d[i].description
                pd.push(d[i])
              }
            }
            powerList.value = pd
            let np = ','+data.authorities+','
            let pcd = []
            for (let i in pd) {
              let hs = util.hasStr(np,','+pd[i].value+',')
              if (hs) {
                pcd.push(pd[i].description)
              }
            }
            powerChecked.value = pcd
          }
          if (r.msgType == 61) {
            clientOptions.value = d
          }
        }
      })
    }

    let sLabel = ref(["150px", "80px", "450px"]);
    let isShow = ref(false);
    let data = reactive({
      flag: "",
      title: "",
      id: "",
      name: "",
      phone: "",
      default_password: "@Android1234",
      password: "",
      password2: "",
      status: 0,
      plat_user: "",
      authorities: null,
      dtCreate: "",
      operCreate: "",
      dtUpdate: "",
      operUpdate: "",
    });
    let loading = ref(false)
    function open(d,f) {
      mqttOnMsg()
      data.flag = f;
      if (f == "add") {
        data.title = "新建操作员";
        data.id = "";
        data.name = "";
        data.phone = "";
        data.password = data.default_password;
        data.password2 = "";
        data.status = 0;
        data.plat_user = "";
        clientName.value = "";
        data.authorities = null
        // data.dtCreate = "";
        // data.operCreate = "";
        // data.dtUpdate = "";
        // data.operUpdate = "";
      } else {
        data.title = '编辑操作员';
        if (data.flag == 'power') data.title = '操作员权限';
        if (data.flag == 'status') data.title = '操作员状态';
        if (data.flag == 'psw') data.title = '重置操作员密码';
        data.id = d.Id;
        data.name = d.name;
        data.phone = d.phone;
        data.password = d.password;
        data.password2 = "";
        data.status = d.status;
        data.plat_user = d.plat_user;
        clientName.value = d.plat_user.name
        data.authorities = d.authorities
        // data.dtCreate = d.dtCreate;
        // data.operCreate = d.operCreate;
        // data.dtUpdate = d.dtUpdate;
        // data.operUpdate = d.operUpdate;
        if (f == "power") {
          getPowers()
        }
      }
      isShow.value = true;
    }
    function close() {
      isShow.value = false;
    }
    function done() {
      let err = ''
      if (util.isNull(data.name)) err = '操作员姓名不能为空'
      else if (isAdmin(data.name)) err = '操作员姓名不能包含“超级管理员”或“默认操作员”字样'
      else if (util.isNull(data.phone)) err = '联系电话不能为空'
      else if (util.isNull(data.plat_user)) err = '所属用户不能为空'
      if (!util.isNull(err)) {
        ElNotification({
            type: 'warning',
            duration: 1500,
            title: '',
            message: err
          })
        return
      }
      loading.value = true
      let msgCode = 52
      if (data.flag == "status") msgCode = 54
      if (data.flag == "power") msgCode = 55
      if (data.flag == "psw") msgCode = 58
      let topic = mqtt.TOPIC_REQ+msgCode
      let p = {}
      p.msgType = msgCode
      p.clientId = user.id
      p.userName = user.username
      let m = {}
      if (hasStr('status,power',data.flag)) m.id = data.id
      if (data.flag == "add") {
        m.name = data.name
        m.phone = 'QBAndroidPlat@'+data.phone
        m.password = data.password
        m.status = data.status
        m.plat_user_id = data.plat_user.Id
      }
      if (data.flag == 'status') {
        m.status = data.status == 0 ? -1 : 0
      }
      if (data.flag == 'power') {
        let pd = powerList.value
        let pcd = JSON.stringify(powerChecked.value)
        let ppd = ''
        for (let i in pd) {
          let hs = util.hasStr(pcd,pd[i].description)
          if (hs) {
            let v = pd[i].value
            if (v == 51) v = '50,51'
            if (v == 61) v = '60,61'
            if (v == 102) v = '101,102'
            if (v == 123) v = '122,123'
            if (v == 135) v = '134,135'
            if (v == 145) v = '144,145'
            if (v == 155) v = '154,155'
            if (v == 165) v = '164,165'
            if (v == 208) v = '206,208'
            if (v == 90200) v = '90200,999001'
            ppd = ppd+','+v
          }
        }
        m.oper_authorities = powerPool.default + ppd
      }  
      if (data.flag == "psw") {
        m.id = data.id
        m.old_pwd = data.password
        m.new_pwd = data.default_password
        p.message = m
      }  
      if (data.flag == "add") {
        p.message = {}
        p.message.operator = JSON.stringify(m)
      } else {
        p.message = m
      }
    //console.log(data.flag+"操作员",JSON.stringify(p))
      mqtt.publish(topic,JSON.stringify(p))
    }
    // 确认msgBox
    function msgBox(flag,msg,title='是否确认？',cbt='确认') {
      ElMessageBox.confirm(msg, title, {
        confirmButtonText: cbt,
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (hasStr('status,psw'),flag) done();
        })
        .catch(() => {});
    }
    // 查询操作员可选权限
    function getPowers() {
      let msgCode = 57
      let topic = mqtt.TOPIC_REQ+msgCode
      let g = {}
      g.msgType = msgCode
      g.clientId = user.id
      g.userName = user.username
      let m = {}
      m.indexPage = 1
      m.pageSize = 1000
      g.message = m
      mqtt.publish(topic,JSON.stringify(g))
    }
    // 查询用户
    let clientName = ref("")
    let clientOptions = ref([])
    function getClientByName(query) {
      let msgCode = 61
      let topic = mqtt.TOPIC_REQ+msgCode
      let g = {}
      g.msgType = msgCode
      g.clientId = user.id
      g.userName = user.username
      let m = {}
      m.name = query
      m.indexPage = 1
      m.pageSize = 10
      g.message = m
      // console.log('查询用户：',JSON.stringify(g))
      mqtt.publish(topic,JSON.stringify(g))
    }
    function clientChange(e) {
      let co = clientOptions.value
      for (let i in co) {
        if (e == co[i].Id) {
          data.plat_user = co[i]
        }
      }
    }
    let powerList = ref([])
    let powerChecked = ref([])
    let allChecked = ref(false)
    function allCheckedAction() {
      let p = powerList.value
      let pc = []
      if (allChecked.value) {
        for (let i in p) {
          pc.push(p[i].description)
        }
      }
      powerChecked.value = pc
    }

    function isNull(v) {
      return util.isNull(v)
    }
    function hasStr(S,k) {
      return util.hasStr(S,k)
    }
    function isAdmin(n) {
      return util.isAdmin(n)
    }

    return {
      user,
      sLabel,
      isShow,
      data,
      open,
      close,
      done,
      msgBox,
      clientName,
      clientOptions,
      loading,
      getClientByName,
      clientChange,
      powerList,
      powerChecked,
      allChecked,
      allCheckedAction,
      isNull,
      hasStr,
      isAdmin
    };
  },
};
</script>

<style lang="scss" scoped>
.form-item{
  display: block;
  .title {
    width: auto;
    padding: 30px;
    padding-bottom: 5px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;
  }
  .power{
    display: block;
    padding:0 30px;
    .item{
      display: inline-block;
      width: auto;
      margin: 5px 10px;
      p{
        padding: 0;
        margin: 0;
      }
    }
  }
}
.form-item-row {
  display: flex;
  flex-direction: row;
  .label {
    background-color: $color-primary-away;
    // border: 1px solid $color-primary-light;
    padding: 0px 15px;
    border-radius: 1px;
  }
}
</style>